package com.pig4cloud.pig.module.controller.mer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.mer.MerTable;
import com.pig4cloud.pig.module.api.entity.product.ProductOrder;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.mer.IMerTableService;
import com.pig4cloud.pig.module.service.product.IProductOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 餐饮店的餐桌列Controller
 *
 * @author ruoyi
 * @date 2023-05-15
 */
@Validated
@Api(value = "餐饮店的餐桌列控制器", tags = {"餐饮店的餐桌列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/mer/table")
public class MerTableController {
    private final IMerTableService merTableService;
    private final IMerService merService;
    private final IProductOrderService productOrderService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 查询餐饮店的餐桌列列表
     */
    @ApiOperation("查询餐饮店的餐桌列列表")
    @PreAuthorize("@pms.hasPermission('module:merTable:list')")
    @GetMapping("/list")
    public TableDataInfo<MerTable> list(@Validated MerTable merTable) {
        QueryWrapper<MerTable> qw = new QueryWrapper<>();
        if (merTable.getMerId()!=null){
            qw.eq("mer_id",merTable.getMerId());
        }
		qw.orderByAsc("table_no");
        TableDataInfo<MerTable> td = PageUtils.buildDataInfo(merTableService.page(PageUtils.buildPage(),qw));
        List<MerTable> list = td.getData();
        for (MerTable table:list){
            if (ObjectUtil.isNotEmpty(table.getMerId())){
                Mer mer = merService.getById(table.getMerId());
                table.setMerName(mer.getShopName());
            }

            if(StrUtil.isNotEmpty(table.getQrCodeUrl())){
                table.setQrCodeUrl(imgUrl + table.getQrCodeUrl());
            }

            Integer[] status = { 0 ,1 };
            QueryWrapper<ProductOrder> qwOrder = new QueryWrapper<>();
            qwOrder.eq("mer_table_id",table.getId());
            qwOrder.eq("order_type", 6);
            qwOrder.in("status", Arrays.asList(status));
            qwOrder.last("limit 1");
            ProductOrder order = productOrderService.getOne(qwOrder);
            if(order!= null){
                table.setOrder(order);
            }
        }
        return td;
    }

    /**
     * 导出餐饮店的餐桌列列表
     */
    @ApiOperation("导出餐饮店的餐桌列列表")
    @PreAuthorize("@pms.hasPermission('module:merTable:export')")
    @SysLog("餐饮店的餐桌列")
    @GetMapping("/export")
    public List export(@Validated MerTable merTable) {
        List<MerTable> list = merTableService.list();
        // ExcelUtil<MerTable> util = new // ExcelUtil<MerTable>(MerTable.class);
        return  list;// util.exportExcel(list, "餐饮店的餐桌列");
    }

    /**
     * 获取餐饮店的餐桌列详细信息
     */
    @ApiOperation("获取餐饮店的餐桌列详细信息")
    @PreAuthorize("@pms.hasPermission('module:merTable:query')")
    @GetMapping("/{id}")
    public R<MerTable> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") String id) {
        MerTable merTable = merTableService.getById(id);
        return R.ok(merTable);
    }

    /**
     * 新增餐饮店的餐桌列
     */
    @ApiOperation("新增餐饮店的餐桌列")
    @PreAuthorize("@pms.hasPermission('module:merTable:add')")
    @SysLog("餐饮店的餐桌列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody MerTable table) {
        boolean bl = merTableService.save(table);
        if(bl){
            try{
                String qrCode = "";
                String fileName = "mer_table_" + table.getTableNo() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/table/info?mer_id=" + table.getMerId()+"&table_id="+table.getId();

                int upload_type = 0;//FileUploadUtils.TYPE_MER_TABLE;
                System.out.println("content:  "+ content);
                String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, table.getTableName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
                qrCode = img_key;
                table.setQrCodeUrl(qrCode);
                bl =  merTableService.updateById(table);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 修改餐饮店的餐桌列
     */
    @ApiOperation("修改餐饮店的餐桌列")
    @PreAuthorize("@pms.hasPermission('module:merTable:edit')")
    @SysLog("餐饮店的餐桌列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody MerTable merTable) {
        return R.okByRow(merTableService.updateById(merTable) ? 1 : 0);
    }

    /**
     * 删除餐饮店的餐桌列
     */
    @ApiOperation("删除餐饮店的餐桌列")
    @PreAuthorize("@pms.hasPermission('module:merTable:remove')")
    @SysLog("餐饮店的餐桌列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable String[] ids) {
        return R.okByRow(merTableService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }



    @SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:merTable:edit')")
    public R<Void> resetQrCode(@RequestBody MerTable table) {
        if(table.getId()!=null){
            try{
                table = merTableService.getById(table.getId());
                if(table != null){
                    String qrCode = "";
                    String fileName = "";
                    String content = "";
                    fileName = "mer_table_" + table.getTableNo() + ".jpg";
                    content = "https://www.sdyuedou.com/wxmini/table/info?mer_id=" + table.getMerId()+"&table_id="+table.getId();

                    int upload_type = 0;//FileUploadUtils.TYPE_MER_TABLE;
                    System.out.println("content:  "+ content);
                    String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, table.getTableName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
                    qrCode = img_key;
                    table.setQrCodeUrl(qrCode);
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (merTableService.updateById(table)) {
                return R.ok();
            }
        }
        return R.failed();
    }

}
